/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define(['i18n', 'services/notifier', 'services/layout'], function (i18n, notifier, L) {

    var editTable = function () {

        // rows and columns of the table
        this.rows = ko.observableArray();
        this.columns = null;

        // table specifications (column type and format, actions, etc..)
        this.specs = null;

        this.defaultItem = ko.observableArray();

        // TODO [qat, 2]: Move keydown outside this viewmodel
        this.keyDown = function (data, event) {
            if (event.which == 13 && this.asErrors().length <= 0) {
                this.rows.push(ko.mapping.fromJS(ko.unwrap(this.defaultItem.pop())));
                this.defaultItem.push(ko.mapping.fromJS(this.dataModel));
            }
            return true;
        }

        // reference to commands
        this.commands = ko.observableArray();
        this.commandsCallback = {};
    };

    // called when 1 of the button is pressed above the table
    editTable.prototype.command = command;
    editTable.prototype.activate = viewActivate;
    editTable.prototype.compositionComplete = viewCompositionComplete;

    return editTable;

    function viewCompositionComplete() {
        L.relayout();
    }

    function viewActivate (settings) {
        L.needsRelayout();

        if(!settings || !settings.specs || !settings.specs.columns) {
            this.rows([]);
            return;
        }

        this.settings = settings;
        this.specs = settings.specs;
        this.columns = settings.specs.columns;
        if(ko.isObservable(settings.items)) {
            this.rows = settings.items;
        } else {
            this.rows(settings.items || []);
        }

        this.dataModel = settings.dataModel;
        this.defaultItem.push(ko.mapping.fromJS(this.dataModel));

        this.asErrors = settings.asErrors;

        // prepare the commands for callbacks
        if (settings.specs.commands) {
            this.commands(settings.specs.commands);

            this.commandsCallback = _.object(_.map(settings.specs.commands, function(cmd) {
                return [cmd.id, cmd.callback];
            }));
        }
    }

    /**
     * if a command is clicked, call the corresponding callback
     * @param commandName
     */
    function command(commandName, item) {
        if (this.commandsCallback[commandName]) {
            this.commandsCallback[commandName](item);
        }
    }

});